const {
    add,
    del,
    edit,
    search,
    searchBy,
    aggregation,
    Page
} = require('../js/mysql.js');

const { dateFormat } = require('@jiess/utils');

let jwt = require('jsonwebtoken');

const router = require('koa-router')()

// 添加新闻接口
router.post('/add', async function (ctx, next) {
    let {
        body
    } = ctx.request;
    let {
        title,
        author,
        date,
        publish,
        content
    } = body;
    let data = await add([title, author, date, content, publish], `news(title,author,date,content,publish) values(?,?,?,?,?)`);
    // console.log(data);
    if (data.affectedRows === 1) {
        ctx.body = {
            msg: "添加成功",
            code: 200,
            data
        }
    } else { 
        ctx.body = {
            msg: '添加失败！',
            code:522
        }
    }
})

// 获取新闻列表接口
router.get('/', async function (ctx, next) {
    let { page, limit } = ctx.query;
    console.log(page);
    console.log(limit);
    let sql1 = `select * from news LIMIT ${(page - 1) * limit},${limit}`;
    let sql2 = `select count(*) as count from news`;
    let data = await Page(sql1);
    let count = await Page(sql2);
    
    let format='yyyy-MM-dd'
    // console.log(45,data);
    ctx.body = {
        msg: '查询成功',
        code: 200,
        data: data.map(item => { 
            item.date = dateFormat(item.date, format);
            return item;
        }),
        count:count[0].count
    }
})


router.prefix('/news');
module.exports = router